package cn.linjianhui.api.client.util;

import org.springframework.util.Assert;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CacheUtils<T> {
    private long cacheMinute;
    private final Object lockObj = new Object();
    private Map<String, CacheObject> cacheMap = new ConcurrentHashMap<>();

    public CacheUtils() {
        this.cacheMinute = 10;
    }

    public CacheUtils(long minute) {
        this.cacheMinute = minute < 0 ? 0 : minute;
    }

    @SuppressWarnings("unchecked")
    public T get(String key) {
        if(this.cacheMinute <= 0.0) return null;
        Assert.hasText(key, "Key value cannot be null");
        CacheObject cacheObject = cacheMap.get(key);
        if(cacheObject != null && Duration.between(cacheObject.getCacheTime(),
                LocalDateTime.now()).toMinutes() > cacheMinute) {
            synchronized (lockObj) {
                cacheMap.remove(key);
            }
        }
        return cacheObject != null ? (T)cacheObject.getCacheData() : null;
    }

    public void set(String key, T value) {
        if(this.cacheMinute <= 0.0) return;
        Assert.hasText(key, "Key value cannot be null");
        if(value == null) return;
        synchronized (lockObj) {
            CacheObject object = new CacheObject();
            object.setCacheData(value);
            object.setCacheTime(LocalDateTime.now());
            cacheMap.put(key, object);
        }
    }

    public void clear() {
        if(cacheMap == null) return;
        synchronized (lockObj) {
            cacheMap.clear();
        }
    }
}
